<template>
	<view class="container">
		<!-- Header with title and icons -->
		<navVue></navVue>
		<!-- 加载动画 -->
		<view class="loading-container" v-if="isLoading">
		    <view class="loading-spinner"></view>
		    <text class="loading-text">加载中...</text>
		</view>
		<!-- Main banner -->
		<view v-else>
			<!-- 主轮播图 -->
		    <swiper class="banner" :indicator-dots="true" indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#fff"
		        autoplay="true" :interval="5000" duration="500" circular="true" @change="onSwiperChange">
		        <swiper-item v-for="(item, index) in limitedBannerList" :key="index">
		            <image :src="item" mode="aspectFill" />
		        </swiper-item>
		    </swiper>
		<!-- 热门推荐 -->
		<view class="section">
			<text class="section-title">5A级景点推荐</text>
			<scroll-view class="scroll-view" scroll-x="true" @scroll="onScroll">
				<view class="scroll-content">
					<!-- 修改scroll-item中的价格部分 -->
					<view class="scroll-item" v-for="(item, index) in hotRecommends" :key="index"
					    @tap="handleNavigateToDetail(item.id)">
					    <image :src="item.image.split(' ')[0]" mode="aspectFill"></image>
					    <text class="item-title-hot">{{item.title}}</text>
					    <view class="price-container">
					        <text class="item-price-hot">¥{{item.price}}</text>
					        <text class="item-original-price" v-if="item.originalPrice > item.price">¥{{item.originalPrice}}</text>
					        <text class="item-discount" v-if="item.originalPrice > item.price">{{item.discount}}折</text>
					    </view>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 精品推荐 -->
		<view class="section">
		    <text class="section-title">旅游景点推荐</text>
		    <view class="grid">
		        <!-- 修改grid-item中的价格部分 -->
		        <view class="grid-item" v-for="(item, index) in featuredRecommends" :key="index"
		            @tap="handleNavigateToDetail(item.id)">
		            <image :src="item.image.split(' ')[0]" mode="aspectFill"></image>
		            <text class="item-title-boutique">{{item.title}}</text>
		            <view class="price-container">
		                <text class="item-price-boutique">¥{{item.price}}</text>
		                <text class="item-original-price" v-if="item.originalPrice > item.price">¥{{item.originalPrice}}</text>
		                <text class="item-discount" v-if="item.originalPrice > item.price">{{item.discount}}折</text>
		            </view>
		        </view>
		    </view>
		</view>
		</view>
		<tabBarVue :current="current"></tabBarVue>
	</view>
</template>

<script>
	import navVue from '../../../components/nav/nav.vue';
	import tabBarVue from '../../../components/tabbar/tabbar.vue';
	import {
		http
	} from '../../../utils/http.js';
	import {
		mapState,
		mapActions
	} from 'pinia'
	import {
		useUserInfoStore
	} from '../../../stores/userInfo.js';
	import {
		getOpenidByCodeAPI
	} from '../../../api/common';

	export default {
		data() {
			return {
				current: 0,
				bannerList: [],
				maxBanners: 4,
				hotRecommends: [],
				featuredRecommends: [],
				isLoading: true, // 新增加载状态
			};
		},
		computed: {
			...mapState(useUserInfoStore, ['id']),
			limitedBannerList() {
				return this.bannerList.flatMap(item => item.split(' ')).slice(0, this.maxBanners);
			}
		},
		components: {
			navVue,
			tabBarVue,
		},
		onShow() {
			uni.hideTabBar({
				animation: false,
			});
			this.current = 0;
		},
		methods: {
			...mapActions(useUserInfoStore, ['setUserInfo']),
			onScroll(e) {
				// 滚动事件处理逻辑
			},
			onSwiperChange(e) {
				// 轮播图变更事件处理逻辑
			},
			async fetchBannerList() {
				try {
					this.isLoading = true;
					const {
						data
					} = await http({
						url: '/api/common/banner',
						method: 'get',
					});
					this.bannerList = data;
				} catch (error) {
					console.error('Error fetching banner list:', error);
				}
			},
			async fetchRecommendations() {
				try {
					const {
						data
					} = await http({
						url: '/api/common/listAll',
						method: 'get',
					});
					 this.hotRecommends = [];
					        this.featuredRecommends = [];
					        data.forEach((item) => {
					            // 计算折扣（基于spotStar星级）
					            let discount = null;
					            // 根据星级生成折扣 (5星:7折, 4星:8折, 3星:9折, 其他:无折扣)
					            if (item.spotStar >= 4 && item.spotStar <= 5) {
					                discount = (8 - (item.spotStar - 4)).toFixed(1); // 5星=7折,4星=8折
					            } else if (item.spotStar === 3) {
					                discount = '9.0'; // 3星=9折
					            }
								 // 计算原价（如果无折扣则原价=现价）
								const originalPrice = discount ? (item.adultFee / (parseFloat(discount) / 10)).toFixed(1) : item.adultFee;
					            
					            const recommendItem = {
					                image: item.imgUrl,
					                title: item.spotName,
					                price: item.adultFee,
					                originalPrice:originalPrice,
					                discount: discount, // 使用计算出的折扣
					                id: item.id
					            };
					            
					            if (item.spotStar >= 5) {
					                this.hotRecommends.push(recommendItem);
					            } else if (item.spotStar >= 1 && item.spotStar <= 4) {
					                this.featuredRecommends.push(recommendItem);
					            }
					        });
				} catch (error) {
					console.error('Error fetching recommendations:', error);
				}finally{
					this.isLoading = false; // 无论成功失败都关闭加载
				}
			},
			handleNavigateToDetail(id) {
				uni.navigateTo({
					url: '/common/pages/details/details?id=' + id
				});


			}
		},
		async mounted() {
			await Promise.all([
			    this.fetchBannerList(),
			    this.fetchRecommendations()
			]);
		}
	}
</script>


<style scoped>
	.container {
	    margin-top: 80rpx;
	    display: flex;
	    flex-direction: column;
	    background-color: #f5f7fa; /* 更柔和的背景色 */
	    overflow: hidden;
	    padding-bottom: 120rpx; /* 为底部导航留出空间 */
	}


	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
	}

	.logo {
		width: 80rpx;
		height: 80rpx;
	}

	.title {
		flex: 1;
		text-align: center;
		font-size: 30rpx;
		font-weight: bold;
	}

	.icons .icon {
		width: 40rpx;
		height: 40rpx;
		margin-left: 10rpx;
	}

	.banner {
	    margin-top: -80rpx;
	    height: 420rpx; /* 稍微增高 */
	    border-radius: 0 0 24rpx 24rpx; /* 底部圆角 */
	    overflow: hidden;
	    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08); /* 添加阴影 */
	}

	.banner image {
	    width: 100%;
	    height: 100%;
	}

	.top-image {
		width: 100%;
		height: 400rpx;
		border-radius: 20rpx;
	}

	.section {
	    margin-top: 40rpx;
	    padding: 0 24rpx;
	}
	
	.section-title {
	    font-size: 36rpx;
	    font-weight: 600; /* 中等粗细 */
	    margin-bottom: 24rpx;
	    padding-left: 0;
	    color: #333;
	    position: relative;
	    display: inline-block;
	}
	
	.section-title::after {
	    content: "";
	    position: absolute;
	    bottom: -8rpx;
	    left: 0;
	    width: 215rpx;
	    height: 6rpx;
	    background-color: #2196F3; /* 蓝色下划线 */
	    border-radius: 2rpx;
	}

	.scroll-view {
	    width: 100%;
	    white-space: nowrap;
	    padding: 0 24rpx;
	    box-sizing: border-box;
	}
	
	.scroll-content {
	    display: inline-flex;
	    gap: 20rpx; /* 使用gap替代margin */
	}
	
	.scroll-item {
	    display: inline-flex;
	    flex-direction: column;
	    width: 280rpx;
	    background-color: #fff;
	    border-radius: 20rpx;
	    overflow: hidden;
	    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	    transition: transform 0.2s;
	}
	
	.scroll-item:active {
	    transform: scale(0.98); /* 点击反馈 */
	}
	
	.scroll-item image {
	    width: 100%;
	    height: 200rpx;
	    border-radius: 20rpx 20rpx 0 0;
	}
	
	.grid {
	    display: grid;
	    grid-template-columns: repeat(2, 1fr);
	    gap: 20rpx;
	    padding: 0 24rpx;
	    margin-bottom: 40rpx;
		
	}
	
	.grid-item {
	    background-color: #fff;
	    border-radius: 20rpx;
	    overflow: hidden;
	    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	    transition: transform 0.2s;
	}
	
	.grid-item:active {
	    transform: scale(0.98);
	}
	
	.grid-item image {
	    width: 100%;
	    height: 280rpx;
	    border-radius: 20rpx 20rpx 0 0;
	}
	.price-container{
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		padding: 0 16rpx 16rpx;
		gap: 8rpx;
	}

	.item-title-hot, .item-title-boutique {
	    font-size: 28rpx;
	    font-weight: 500;
	    white-space: nowrap;
	    overflow: hidden;
	    text-overflow: ellipsis;
	    padding: 16rpx 16rpx 8rpx;
	}

	.item-price-hot,.item-price-boutique {
	    color: #ff4d4f;
	    font-size: 28rpx;
	    font-weight: 600;
	}
	.item-original-price {
	    color: #999;
	    font-size: 24rpx;
	    text-decoration: line-through;
	    margin-left: 4rpx;
	}
	
	.item-discount {
	    background-color: #fff2f0;
	    color: #ff4d4f;
	    font-size: 22rpx;
	    padding: 2rpx 8rpx;
	    border-radius: 4rpx;
	    border: 1rpx solid #ffccc7;
		font-family: Arial, sans-serif; /* 确保小数点对齐 */
	}

	/* 移除原来的省略号样式 */
	.ellipsis {
	    display: none;
	}
	/* 加载动画样式 */
	.loading-container {
	    display: flex;
	    flex-direction: column;
	    justify-content: center;
	    align-items: center;
	    height: 60vh;
	}
	
	.loading-spinner {
	    width: 80rpx;
	    height: 80rpx;
	    border: 8rpx solid #f3f3f3;
	    border-top: 8rpx solid #2196F3;
	    border-radius: 50%;
	    animation: spin 1s linear infinite;
	    margin-bottom: 20rpx;
	}
	
	.loading-text {
	    font-size: 28rpx;
	    color: #666;
	}
	
	@keyframes spin {
	    0% { transform: rotate(0deg); }
	    100% { transform: rotate(360deg); }
	}
	
</style>